package com.bite.common.core.utils;

import com.bite.common.core.constants.CacheConstants;
import com.bite.common.core.constants.JwtConstants;
import com.bite.common.redis.service.RedisService;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 均先生
 */
public class JwtUtils {
    /**
     * ⽣成令牌
     *
     * @param claims 数据
     * @param secret 密钥
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims, String secret) {
        return Jwts.builder().setClaims(claims).signWith(SignatureAlgorithm.HS512, secret).compact();
    }
    /**
     * 从令牌中获取数据
     *
     * @param token 令牌
     * @param secret 密钥
     * @return 数据
     */
    public static Claims parseToken(String token, String secret) {
        return
                Jwts.parser().setSigningKey(secret).parseClaimsJws(token).getBody();
    }

    public static String getUserKey(Claims claims) {
        Object value = claims.get(JwtConstants.LOGIN_USER_KEY);
        return toStr(value);
    }

    public static String getUserId(Claims claims) {
        Object value = claims.get(JwtConstants.LOGIN_USER_ID);
        return toStr(value);
    }



    private static String toStr(Object value) {
        if (value == null) {
            return "";
        }
        return value.toString();
    }

    public static void main(String[] args) {
        /*Map<String,Object> claim = new HashMap<>();
        claim.put("userId",123456789L);
        System.out.println(createToken(claim,"zxskcik2ei8c4jdhv2"));*/

        String token = "eyJhbGciOiJIUzUxMiJ9.eyJ1c2VySWQiOjEyMzQ1Njc4OX0.GyLAFX3Ch2mzvV7owTeHGjGstn3g2V2J7p04qyswnENhykbXJwugt8fo0t3HMDw-xFr2XSSPT4X849F1GRrnVw";
        Claims claims = parseToken(token,"zxskcik2ei8c4jdhv2");
        System.out.println(claims);

        // 用户登录成功调用createToken生成令牌并发给前端，
    }
}
